package com.empresa.iflex.core;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.Toast;

import com.androidplot.series.XYSeries;
import com.androidplot.ui.layout.AnchorPosition;
import com.androidplot.ui.layout.DynamicTableModel;
import com.androidplot.ui.layout.SizeLayoutType;
import com.androidplot.ui.layout.SizeMetrics;
import com.androidplot.ui.layout.XLayoutStyle;
import com.androidplot.ui.layout.YLayoutStyle;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;
import com.empresa.iflex.R;
import com.empresa.iflex.database.IFlexDbAdapter;
 
public class Grafico extends Activity{
 
    private XYPlot mySimpleXYPlot;
	private int cursor_count = 0;
	private XYSeries series1, series2;
	private int maior_media, menor_media;
	private IFlexDbAdapter ida;
	private SQLiteDatabase db;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grafico);
        
        criaGrafico();	//cria grafico, tamanho, cores...
        
        try {
			this.ida = new IFlexDbAdapter(getApplicationContext());
			this.db = ida.open();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Erro ao abrir Banco de Dados! Desculpe.", Toast.LENGTH_SHORT).show();
			finish();

		}
        
    	Cursor c = Percurso.findAllMedias(db);    	
        this.cursor_count = c.getCount();       
        
        povoaGrafico(c); //preenche grafico com dados do cursor       
        c.close();
    }
    
    private void criaGrafico() {
    	// Initialize our XYPlot reference:
        this.mySimpleXYPlot = (XYPlot) findViewById(R.id.mySimpleXYPlot);
        
        //mySimpleXYPlot.setDomainStep(XYStepMode.SUBDIVIDE, 5);
        
        // draw a domain line for every element plotted on the domain:
        this.mySimpleXYPlot.setDomainStep(XYStepMode.SUBDIVIDE, 10);
        this.mySimpleXYPlot.setRangeStep(XYStepMode.SUBDIVIDE, 15);
        this.mySimpleXYPlot.setRangeLowerBoundary(0, BoundaryMode.AUTO);
        
        // get rid of the decimal place on the display:
        this.mySimpleXYPlot.setDomainValueFormat(new DecimalFormat("#"));
        this.mySimpleXYPlot.setRangeValueFormat(new DecimalFormat("#"));
        
        // use a 2x2 grid:
        this.mySimpleXYPlot.getLegendWidget().setTableModel(new DynamicTableModel(1, 2));
 
        // adjust the legend size so there is enough room
        // to draw the new legend grid:
        this.mySimpleXYPlot.getLegendWidget().setSize(new SizeMetrics(60, SizeLayoutType.ABSOLUTE, 100, SizeLayoutType.ABSOLUTE));
 
        // add a semi-transparent black background to the legend
        // so it's easier to see overlaid on top of our plot:
        Paint bgPaint = new Paint();
        bgPaint.setColor(Color.BLACK);
        bgPaint.setStyle(Paint.Style.FILL);
        bgPaint.setAlpha(140);
        this.mySimpleXYPlot.getLegendWidget().setBackgroundPaint(bgPaint);
 
        // adjust the padding of the legend widget to look a little nicer:
        this.mySimpleXYPlot.getLegendWidget().setPadding(10, 1, 1, 1);
 
        // reposition the grid so that it rests above the bottom-left
        // edge of the graph widget:
        this.mySimpleXYPlot.position(
        		this.mySimpleXYPlot.getLegendWidget(),
                20,
                XLayoutStyle.ABSOLUTE_FROM_RIGHT,
                35,
                YLayoutStyle.ABSOLUTE_FROM_BOTTOM,
                AnchorPosition.RIGHT_BOTTOM);
 
 
        // Reduce the number of range labels
        this.mySimpleXYPlot.setTicksPerRangeLabel(3);
        
        this.mySimpleXYPlot.setPlotMargins(0, 0, 0, 0);
        this.mySimpleXYPlot.setPlotPadding(10, 10, 10, 10);
        
        this.mySimpleXYPlot.getGraphWidget().setMarginTop(2);
        this.mySimpleXYPlot.getGraphWidget().setMarginRight(2);
        this.mySimpleXYPlot.setBorderStyle(XYPlot.BorderStyle.SQUARE, null, null);
 
        // By default, AndroidPlot displays developer guides to aid in laying out your plot.
        // To get rid of them call disableAllMarkup():
        mySimpleXYPlot.disableAllMarkup();
	}
    
    public void povoaGrafico(Cursor cur){
        List<Float> list_etanol = new ArrayList<Float>();
        List<Float> list_gasolina = new ArrayList<Float>();
        
    	this.maior_media = Math.round(Percurso.getBiggestMedia(this.db));
    	this.menor_media = Math.round(Percurso.getLowerMedia(this.db));
    	if (menor_media < 2){
    		menor_media = 2;
    	}
    	this.mySimpleXYPlot.setRangeUpperBoundary(maior_media+2, BoundaryMode.AUTO);
    	this.mySimpleXYPlot.setRangeLowerBoundary(menor_media-2, BoundaryMode.AUTO);
        
    	if (cur.moveToFirst()){
	        do {
	        	if(cur.getString(cur.getColumnIndex("combustivel")).equalsIgnoreCase("etanol")){
	        		list_etanol.add(cur.getFloat(cur.getColumnIndex("media")));
	        	}else if(cur.getString(cur.getColumnIndex("combustivel")).equalsIgnoreCase("gasolina")){
	        		list_gasolina.add(cur.getFloat(cur.getColumnIndex("media")));
	        	}
	        }while (cur.moveToNext());
    	}
    	
        cur.close();
        
        // Turn the above arrays into XYSeries:
        this.series1 = new SimpleXYSeries(list_etanol, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Etanol");

        this.series2 = new SimpleXYSeries(list_gasolina, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, 
                "Gasolina");
        
        //FIXME (ainda com problema) Gambiarra FORTE! Pra povoar grafico igualmente sempre
        int num_etanol = list_etanol.size();
        int num_gasolina = list_gasolina.size();
        
/*        if (num_etanol < num_gasolina){
        	list_etanol.add(num_gasolina-1, Percurso.getLastMedia(db, "etanol"));
        }else if (num_etanol > num_gasolina){
        	list_gasolina.add(num_etanol-1, Percurso.getLastMedia(db, "gasolina"));
        }*/
        
        if ((num_etanol != 0) && (num_gasolina != 0)){
	        if (num_etanol < num_gasolina){
	        	SimpleXYSeries sxy = (SimpleXYSeries) series1;
	        	sxy.addLast(num_gasolina-1, Percurso.getLastMedia(db, "etanol"));
	        	this.series1 = sxy;
	        	num_etanol = num_gasolina;
	        }else if (num_etanol > num_gasolina){
	        	SimpleXYSeries sxy = (SimpleXYSeries) series2;
	        	sxy.addLast(num_etanol-1, Percurso.getLastMedia(db, "gasolina"));
	        	this.series2 = sxy;
	        	num_gasolina = num_etanol;
	        }
        }


        	if(num_etanol == 1){
        		SimpleXYSeries sxy = (SimpleXYSeries) series1;
	        	sxy.addLast(1, Percurso.getLastMedia(db, "etanol"));
	        	this.series1 = sxy;
        	}
        	if (num_gasolina == 1){
        		SimpleXYSeries sxy = (SimpleXYSeries) series2;
	        	sxy.addLast(1, Percurso.getLastMedia(db, "gasolina"));
	        	this.series2 = sxy;
        	}

 
        // Create a formatter to use for drawing a series using LineAndPointRenderer:
        LineAndPointFormatter series1Format = new LineAndPointFormatter(
                Color.rgb(0, 200, 0),                   // line color
                Color.rgb(0, 100, 0), null);                   // point color
 
        // Add series1 to the xyplot:
        this.mySimpleXYPlot.addSeries(series1, series1Format);
 
        // Same as above, with series2:
        this.mySimpleXYPlot.addSeries(series2, new LineAndPointFormatter(Color.rgb(0, 0, 200), Color.rgb(0, 0, 100),
                null));
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	Cursor c = Percurso.findAllMedias(db);
    	
    	if (c.getCount() < cursor_count){
    		this.mySimpleXYPlot.removeSeries(series1);
    		this.mySimpleXYPlot.removeSeries(series2);
    		povoaGrafico(c);
    	}
        c.close();
    }
    
    @Override
    public void onDestroy(){
    	super.onDestroy();
    	if (db != null){
			db.close();
			ida.close();
    	}

    	
    }
    
}